<?php


namespace PKApp\DataBase;


use PKApp\DataBase\Classes\DataBaseController;
use PKApp\DataBase\Classes\DataBaseService;
use PKFrame\DataHandler\Arrays;

class AdminSetBackup extends DataBaseController
{

    public function __construct()
    {
        parent::__construct();
        $this->service = new DataBaseService();
    }

    public function Main()
    {
        $list_table = request()->post('list');
        $index_table = request()->post('index');
        $name_table = $list_table[$index_table];
        $sql_entity_table = $this->service->GetEntityByTable($name_table);
        fileHelper()->PutContents($this->getPathBackup(), self::FileName_Table,
            $sql_entity_table . "\r\n", false);
        $sql_list_data = $this->service->GetListByData($name_table);
        $mode = '';
        $count_write_length = 0;
        if (Arrays::Is($sql_list_data)) {
            $mode = 'list';
            $count_write_length = [];
            foreach ($sql_list_data as $index => $sql_list_datum) {
                $count_write_length[] = fileHelper()->PutContents($this->getPathBackup() . DS,
                    $name_table . '_' . $index . '.sql', $sql_list_datum);
            }
        } elseif (!empty($sql_list_data)) {
            $mode = 'once';
            $count_write_length = fileHelper()->PutContents($this->getPathBackup() . DS, $name_table . '.sql', $sql_list_data);
        }
        $this->json(['name' => $name_table, 'mode' => $mode,
            'count_write_length' => $count_write_length], $this->service->count_rows);
    }

    public function GetListByTableName()
    {
        fileHelper()->RemoveDir($this->getPathBackup());
        $list_table = $this->service->GetListByTableName();
        $this->json($list_table, count($list_table));
    }

    public function DelBySQLFile()
    {
        $name_file = request()->post('file_name');
        fileHelper()->UnLink($this->getPathBackup() . DS . $name_file);
        $this->json();
    }

}